﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.IO;

namespace Quebec.Silverlight.Utilities
{
	public static class StorageHandler<T>
	{
		/// <summary>
		/// Add value to file in Application store. If key already exists
		/// it will be deleted and added again.
		/// </summary>
		/// <param name="key"></param>
		/// <param name="value"></param>
		public static void StoreToFile(string filename, T obj)
		{
			IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
			using (IsolatedStorageFileStream fileStream = appStore.OpenFile(filename, FileMode.Create))
			{
				DataContractSerializer serializer = new DataContractSerializer(typeof(T));
				serializer.WriteObject(fileStream, obj);
			}
		}

		/// <summary>
		/// Read file from Application store. If the key is not 
		/// found null is returned.
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public static T RetrieveFromFile(string filename)
		{
			T obj = default(T);
			IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
			if (appStore.FileExists(filename))
			{
				using (IsolatedStorageFileStream fileStream = appStore.OpenFile(filename, FileMode.Open))
				{
					DataContractSerializer serializer = new DataContractSerializer(typeof(T));
					obj = (T)serializer.ReadObject(fileStream);
				}
			}
			return obj;
		}

		/// <summary>
		/// Add value to ApplicationSettings. If key already exists
		/// it will be deleted and added again.
		/// </summary>
		/// <param name="key"></param>
		/// <param name="value"></param>
		public static void StoreToSetting(string key, T obj)
		{
			IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

			if (settings.Contains(key))
				settings.Remove(key);

			settings.Add(key, obj);
		}

		/// <summary>
		/// Read value from ApplicationSettings. If the key is not 
		/// found null is returned.
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public static T RetrieveFromSetting(string key)
		{
			IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

			if (settings.Contains(key))
			{
				return (T)settings[key];
			}

			return default(T);
		}
	}
}
